import { useEffect, useState } from 'react';
import { Form, Input, Tree, Modal } from 'antd';
import { getRoutes } from '../../../api/role'
const { TextArea } = Input;

export interface Item {
  key?: string | number;
  name?: string;
  rowKey?: string;
  roles?: string;
  description?: string;
  createUser?: string;
  updateTime?: string;
  [prototype: string]: any;
}

const TreeModal = (props: any) => {
  //（受控）展开指定的树节点
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  // 选中复选框的树节点
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  let { routes } = props;
  let treeData: any = [];
  let arrList: any[] = [];
  let arrCheck: any[] = [];
  const treeAddId = (t: any, key: string) => {
    for (let i = 0; i < t.length; i++) {
      const keyId = key + '-' + i;
      t[i]['key'] = keyId;
      if(t[i]['select'] === 1) {
        arrList.push(t[i]['key'])
        arrCheck.push(key)
      }
      if(t[i].children) {
        treeAddId(t[i].children, keyId)
      }
    }
  }
  if(routes) {
    treeData = JSON.parse(JSON.stringify(routes));
    treeData.filter((t: any, i: number) => {
      const key = '0-' + i;
      t['key'] = key
      if(t['select'] === 1) {
        arrList.push(t['key'])
        arrCheck.push(t['key'])
      } else {

      }
      if(t.children) {
        treeAddId(t.children, key)
      } else {

      }
      return t
    })
  } 
  useEffect(() => {
    setCheckedKeys([...arrList]);
    setExpandedKeys([...arrCheck]);
  }, [])

  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: any) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  return (
    <Tree
      checkable
      onExpand={onExpand}
      expandedKeys={expandedKeys}
      autoExpandParent={autoExpandParent}
      onCheck={onCheck}
      checkedKeys={checkedKeys}
      onSelect={onSelect}
      selectedKeys={selectedKeys}
      treeData={treeData}
    />
  );
};

const DialogModalForm = (props: any) => {

  const [formDialog] = Form.useForm();
  let { dialogVisible, handleSetDialogVisible, dialogType, record } = props;
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [routes, setRoutes] = useState(record?.routes || []);
  
  // 弹框表单
  
  useEffect(() => {
    if(record) {
      formDialog.setFieldsValue({...record})
    }
    if(!routes.length) {
      (async function() {
        let result = await getRoutes();
        setRoutes(result.data)
      })();
    } else {

    }
  }, [record, formDialog, routes])

  const handleOk = () => {
    setConfirmLoading(true)
    console.log(Object.assign(formDialog.getFieldsValue(), {key: record?.key}), '提交')
    setTimeout(() => {
      setConfirmLoading(false)
      handleSetDialogVisible(false)
    }, 2000)
  };

  const handleCancel = () => {
    handleSetDialogVisible(false);
    formDialog.resetFields();
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };
  // const validateMessages = {
  //   required: '${label} is required!',
  // };

  return (
    <Modal forceRender 
      title={dialogType} 
      visible={dialogVisible} 
      onOk={handleOk} 
      onCancel={handleCancel} 
      confirmLoading={confirmLoading}
    >
      <Form
        form={formDialog} {...layout} 
        // validateMessages={validateMessages}
      >
        <Form.Item name="name" label="角色名称" rules={[{ required: true }]}>
          <Input placeholder="请输入角色名称" />
        </Form.Item>
        <Form.Item name="roleKey" label="角色代码">
          <Input placeholder="请输入角色代码" />
        </Form.Item>
        <Form.Item name="description" label="角色描述">
          <TextArea rows={3} placeholder="请输入角色描述" />
        </Form.Item>
        <Form.Item name="roles" label="角色权限">
          <TreeModal routes={routes}/> 
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default DialogModalForm;
